package com.atguigu.day03;

import com.atguigu.utils.SensorReading;
import com.atguigu.utils.SensorSource;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

// 检测传感器连续1s温度上升
public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new SensorSource())
                .keyBy(r -> r.sensorId)
                .process(new Alert())
                .print();

        env.execute();
    }

    public static class Alert extends KeyedProcessFunction<String, SensorReading, String> {
        private ValueState<Integer> lastTemp; // 用来保存最近一次温度值
        private ValueState<Long> timerTs;     // 用来保存报警定时器的时间戳
        @Override
        public void open(Configuration parameters) throws Exception {
            lastTemp = getRuntimeContext().getState(
                    new ValueStateDescriptor<Integer>("last-temp", Types.INT)
            );
            timerTs = getRuntimeContext().getState(
                    new ValueStateDescriptor<Long>("timer-ts", Types.LONG)
            );
        }

        // 1 2 3 4 5 6 7 8 9 10
        // 1 2 3 4 5 1
        @Override
        public void processElement(SensorReading value, Context ctx, Collector<String> out) throws Exception {
            Integer prevTemp = null;
            // 将最近一次温度值取出
            if (lastTemp.value() != null) prevTemp = lastTemp.value();
            lastTemp.update(value.temperature); // 将当前温度值存入状态变量

            Long ts = null;
            if (timerTs.value() != null) ts = timerTs.value();

            if (prevTemp != null) {
                // 温度下降且存在报警定时器的情况
                if (value.temperature < prevTemp && ts != null) {
                    // 将定时器删除
                    ctx.timerService().deleteProcessingTimeTimer(ts);
                    // 清空保存时间戳的状态变量
                    timerTs.clear();
                }
                // 温度上升且不存在报警定时器的情况
                else if (value.temperature > prevTemp && ts == null) {
                    // 注册定时器
                    long oneSecondLater = ctx.timerService().currentProcessingTime() + 1000L;
                    ctx.timerService().registerProcessingTimeTimer(oneSecondLater);
                    // 将定时器时间戳保存下来
                    timerTs.update(oneSecondLater);
                }
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            out.collect("温度传感器：" + ctx.getCurrentKey() + " 连续1秒钟温度上升！");
            // 注意这里要清空
            timerTs.clear();
        }
    }
}
